package NG::Gen::Users::Level;
use strict;
use warnings;
use utf8;

sub level_after_create {
	my $self = shift;
	my $step = $self->{parent}{app}->reference("user_levels")->get_by_key(1);
	unless($step){
		return "cannot found first step";
	}
	$self->update_data({
			level => $step->{level},
			experience => $step->{experience},
			step => $step->{entry},
			l_point => $step->{l_point},
			u_point => $step->{u_point},
			money => $step->{money},
			bonus => $step->{bonus},
			category => $step->{user_cat},
		});
	return undef;
}
sub level_before_remove {
	my $self = shift;
}
sub add_experience {
	my $self = shift;
	my $add = shift;
	my $ref = $self->{parent}{app}->reference("user_levels");

	my $added = 0;
	while($add > 0){
		my $cur = $ref->get_by_key($self->step);
		if($cur->{last}){
			last;
		}
		my $next = $ref->get_by_key($self->step+1);
		unless($next){
			last;
		}
		my $diff = $next->{experience} - $self->experience;
		if($add < $diff){
			$self->experience($self->experience + $add);
			$added += $add;
			last;
		}
		$added += $diff;
		$add -= $diff;

		$self->update_data({
				category => $next->{user_cat},
				level => $next->{level},
				experience => $next->{experience},
				step => $next->{entry},
				l_point => $self->l_point + $next->{l_point},
				u_point => $self->u_point + $next->{u_point},
				money => $self->money + $next->{money},
				bonus => $self->bonus + $next->{bonus},
				fame => 0,
			});
	}
	return $added;
}
sub next_experience {
	my $self = shift;
	my $ref = $self->{parent}{app}->reference("user_levels");
	my $cur = $ref->get_by_key($self->step);
	if($cur->{last}){
		return $self->{parent}{app}->reference("user_levels")->get_by_key($self->step+1);
	}
	return undef;
}

1;
